/**
 * 获取终端类型
 */
const getTerminalType = function () {
  let result = 'other'
  let userAgent = navigator.userAgent || navigator.vendor || window.opera || '';
  if (/android/i.test(userAgent)) {
    result = 'android'
  } else if (/(iPhone|iPad|iPod)/i.test(userAgent)) {
    result = 'ios'
  }
  return result
}

/**
 * 获取浏览器环境类型
 */
const getBrowserType = function () {
  let result = 'other'
  const userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('micromessenger') !== -1) {
    return 'wechat';
  } else if (userAgent.indexOf('alipayclient') !== -1) {
    return 'alipay';
  }
  return result;
}

/**
 * 获取Url地址中参数
 * @param {String} url 可有可无
 */
const getUrlParams = function (url) {
  url = url || location.href
  let result = {}
  let search = url.split('?')[1] || ''
  let params = search.split('&')
  params.forEach(function (v) {
    let [key, val] = v.split('=')
    key && (result[key] = val || '')
  })
  return result
}

/**
 * JSON字符串格式化
 * @param {String} jsonStr
 * @param {*} defaultValue
 */
const jsonParse = function (jsonStr, defaultValue) {
  let result = defaultValue || {}
  if (jsonStr) {
    try {
      result = JSON.parse(jsonStr)
    } catch (err) {
      if (err && err.message === `Unexpected token ' in JSON at position 1`) {
        try {
          result = eval('(' + jsonStr + ')')
        } catch (err) {
          console.log('jsonParse:', err)
          result = defaultValue || {}
        }
      } else {
        result = defaultValue || {}
      }
    }
  }
  return result
}
